#include "bookstore.h"
#include "init.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "book.h"
#include "student.h"
#include "studentstore.h"
//#include <QDateTime>
#include <time.h>
using namespace bookandrecord;
using namespace utils;
using namespace student;
using namespace studentstore;

namespace bookstore {
//相当于构造函数（调用创造book）
Menu* createMenu() {
    Menu* menu = new Menu();
    memset(menu, 0, sizeof (Menu));//所有信息先赋值为0
    menu->countNum = 1;
    menu->remain = menu->countNum;
    return menu;
}
//countNum表示书的多少
Menu* createMenu(string name, string writer, string ISBN, string publish) {
    Menu* menu = new Menu;
    memset(menu, 0, sizeof (Menu));//所有信息先赋值为0
    menu->ID = -1;
    strcpy(menu->name, &name[0]);
    strcpy(menu->writer, &writer[0]);

    strcpy(menu->publish, &publish[0]);
    if(ISBN.size() == 0) {
        strcpy(menu->ISBN, to_string(menu->ID).data());
    } else
        strcpy(menu->ISBN, &ISBN[0]);
    menu->borrowCount = 0;
    menu->exist = 1;

    //先设置为0，数量增加由addBook实现
    menu->countNum = 0;
    menu->remain = 0;
    menu->remain = 0;
    menu->reserveNum = 0;

    return menu;
}
Book* createBook(int menu_id) {
    Book* book = new Book();
    memset(book, 0, sizeof (Book));//所有信息先赋值为0
    book->ID = -1;
    book->menu_ID = menu_id;
    book->exist = 1;        //1代表存在
    book->isBorrowed = -1;   //借阅状态：未借出-1
    book->isBooked = -1;       //预约状态：未预约-1
    book->book_cond = 0;    //本书状态：正常0
    book->borrow_num = 0;      //被借阅次数
    return book;
}

Book* createBook() {
    Book* book = new Book();
    memset(book, 0, sizeof (Book));//所有信息先赋值为0
    return book;
}


//添加书籍,为了做成多册入库
bool addBook(Book* book, int count) {
    auto size = sizeof (Book);                //书籍类的大小
    FILE *file = openfile(bookDatPath, size); //打开文件

    for(int i = 0; i < count; i++) {    //多册入库
        fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾
        auto offset = ftell(file);//ftell得到文件从指针到文件头的大小（offset是文件总大小）
        book->ID = offset / size; //确定ID大小
        fwrite(book, size, 1, file);//将book内容写入文件
        addLog("[addBook] status 0 : Add bookID[" + to_string(book->ID) + "] in menuID[" + to_string(book->menu_ID) + "] successfully");
    }

    fclose(file);//关闭文件

    //实现book对应的menu数据更新
    Menu* tempMenu = new Menu;
    tempMenu = search<Menu>(book->menu_ID, menuDatPath);
    tempMenu->countNum += count;
    tempMenu->remain += count;


    rewrite(book->menu_ID, tempMenu, menuDatPath);
    return 1;//返回1表示添加成功
}

//成功0，成功且menu也删除了1，书籍正在被借阅-1，书籍正在被预约 -2
int deleteBook(int book_id) {

    Book * book = new Book;   //准确查找
    book = search<Book>(book_id, bookDatPath);
    Menu * menu = new Menu;
    menu = search<Menu>(book->menu_ID, menuDatPath);

    //返回-1，书籍正在被借阅
    if(book->isBorrowed != -1) {
        addLog("[deleteBook] status -1 : The book is borrowed. Delete bookID[" + to_string(book->ID) + "] unsuccessfully");
        return -1;
    }
    //返回-2，书籍正在被预约
    else if(book->isBooked != -1) {
        addLog("[deleteBook] status -2 : The book is reserved. Delete bookID[" + to_string(book->ID) + "] unsuccessfully");
        return -2;
    }
    //返回0，正常
    else {
        deleteItem<Book>(book_id, bookDatPath);
        menu->remain -= 1;
        menu->countNum -= 1;
        rewrite<Menu>(menu->ID, menu, menuDatPath);

        //返回1，若menu剩余0本则删除menu
        if(menu->countNum == 0) {
            deleteItem<Menu>(menu->ID, menuDatPath);
            addLog("[deleteBook] status 1 : Delete bookID[" + to_string(book->ID) + "] successfully and menuID[" + to_string(menu->ID) + "] is also deleted");
            return 1;
        }

        //正常还书
        addLog("[deleteBook] status 0 : Delete bookID[" + to_string(book->ID) + "] successfully");
        return 0;
    }
}

//成功0，目录中有书籍正在被借阅-1，目录中有书籍正在被预约 -2
int deleteMenu(int menu_id) {
    Menu * menu = new Menu;
    menu = search<Menu>(menu_id, menuDatPath);

    vector<Book*> booklist = search_multiplebookReturn("notFuzzySearch", "menu_id", menu->ID, bookDatPath);

    //逐个判断menu对应的每一本书是否被借阅或预约
    for(int i = 0; i < booklist.size(); i++) {
        //是否被借阅
        if(booklist[i]->isBorrowed != -1) {
            addLog("[deleteMenu] status -1 : A book is borrowed. Delete menuID[" + to_string(menu->ID) + "] unsuccessfully");
            return -1;
        }
        //是否被预约
        else if (booklist[i]->isBooked != -1) {
            addLog("[deleteMenu] status -2 : A book is booked. Delete menuID[" + to_string(menu->ID) + "] unsuccessfully");
            return -2;
        }
    }

    //正常删除
    for(int i = 0; i < booklist.size(); i++) {
        deleteBook(booklist[i]->ID);
    }
    addLog("[deleteMenu] status 0 : Delete menuID[" + to_string(menu->ID) + "] successfully");
    return 0;
}

//添加menu并执行多册入库
bool addMenu(Menu* menu, int count) {
    auto size = sizeof (Menu);                //书籍类的大小
    FILE *file = openfile(menuDatPath, size); //打开文件
    if (menu->ID == -1) { //初始化ID为-1，若ID为-1则表示该学生是新用户
        fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾
        auto offset = ftell(file);//ftell得到文件从指针到文件头的大小（offset是文件总大小）
        menu->ID = offset / size; //确定ID大小
        if(strcmp(menu->ISBN, to_string(-1).data()) == 0) {
            strcpy(menu->ISBN, to_string(menu->ID).data());
        }
        fwrite(menu, size, 1, file);//将book内容写入文件

    } else {
        //已存在ID，表示不是新用户可以进行文件修改
        fseek(file, size * menu->ID, SEEK_SET);//将文件指针移到文件第ID个学生后
        fwrite(menu, size, 1, file);//将student内容写入文件
    }
    fclose(file);//关闭文件

    //多册入库
    Book* book = new Book;
    book = createBook(menu->ID);
    addBook(book, count);
    addLog("[addMenu] status 0 : Add " + to_string(count) + " books to menuID[" + to_string(book->menu_ID) + "] successfully");
    return 1;//返回1表示添加成功
}


Record* createRecord() {
    Record* record = new Record();
    memset(record, 0, sizeof (Record));//所有信息先赋值为0
    return record;
}

//添加记录，自动读取时间
int addRecord(int user_id, int book_id) {
    auto size = sizeof (Record);//学生类的大小
    FILE *file = openfile(recordDatPath, size); //打开文件
    Record *record = new Record; //新建临时文件
    fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾
    auto offset = ftell(file);//ftell得到文件从指针到文件头的大小（offset是文件总大小）
    record->ID = offset / size; //确定ID大小
    record->bookId = book_id;
    record->userId = user_id;
    time_t timep;
    time(&timep);
    record->borrowTime =  timep;   //初始化借阅时间
    record->latestReturnTime =   timep + BORROWING_TIME;  //初始化最迟还书时间
    record->returnTime = 0;
    record->status = 1;
    record->isReborrwed = 0;
    fwrite(record, size, 1, file);//将student内容写入文件
    fclose(file);//关闭文件

    return record->ID;
}

//收藏，成功返回收藏数组的位置，已经被收藏返回-1，其他返回-2
int addstar(int user_id, Menu *menu) {
    Student *stu = search<Student>(user_id, studentDatPath);

    //清理收藏夹中已被删除的书籍
    for(int i = 0; i < MAX_STAR; i++) {
        int menu_id = stu->star[i];
        if(menu_id != -1) {
            Menu *menu = search<Menu>(menu_id, menuDatPath);
            if(menu->exist == 0) {
                stu->star[i] = -1;
            }
        }
    }


    int canstar = -1;
    for(int i = 0; i < MAX_STAR; i++) {
        if(stu->star[i] == menu->ID) {
            canstar = -2;
            break;
        }
        if(stu->star[i] == -1) {
            canstar = i;
            break;
        }
    }
    if(canstar == -1) {
        addLog("[star] status -1: Star file is full. UserID[" + to_string(stu->ID) + "] star menuID[" + to_string(menu->ID) + "] unsuccessfully");

        return -2;
    } else if(canstar == -2) {
        addLog("[star] status -2: This menu has been stared by you. UserID[" + to_string(stu->ID) + "] star menuID[" + to_string(menu->ID) + "] unsuccessfully");
        return -1;
    } else {
        stu->star[canstar] = menu->ID;
        rewrite(stu->ID, stu, studentDatPath);
        addLog("[star] status 0: UserID[" + to_string(stu->ID) + "] star menuID[" + to_string(menu->ID) + "] successfully");

        return canstar;
    }
}

//取消收藏，成功返回1，否则返回0
int delstar(int user_id, string isbn) {
    Student *stu = search<Student>(user_id, studentDatPath);
    Menu *menu = search_onemenuReturn(isbn, menuDatPath);
    int stars = -1;
    for(int i = 0; i < MAX_STAR; i++) {
        if(stu->star[i] == menu->ID) {
            stars = i;
        }
    }
    if(stars == 2) {
        stu->star[stars] = -1;
        rewrite(user_id, stu, studentDatPath);
        return 1;
    } else if(stars == 1) {
        stu->star[stars] = stu->star[stars + 1];
        stu->star[stars + 1] = -1;
        rewrite(user_id, stu, studentDatPath);
        return 1;
    } else if(stars == 0) {
        stu->star[stars] = stu->star[stars + 1];
        stu->star[stars + 1] = stu->star[stars + 2];
        stu->star[stars + 2] = -1;
        rewrite(user_id, stu, studentDatPath);
        addLog("[unstar] status 0: UserID[" + to_string(stu->ID) + "] unstar menuID[" + to_string(menu->ID) + "] successfully");
        return 1;
    } else {
        addLog("[star] status 1: UserID[" + to_string(stu->ID) + "] star menuID[" + to_string(menu->ID) + "] unsuccessfully");
        return 0;
    }
}



//借书, 0成功借阅， 1成功借阅并加入英雄榜， -1 借书超上限， -2 该书正在被借阅-3有人正在预约
//给出提示
int borrow(int user_id, int book_id) {
//    cout << "start borrow" << endl;


    Student * user = new Student();   //准确查找
    user = search<Student>(user_id, studentDatPath); //user中间变量
    Book * book = new Book();    //book中间变量
    book = search<Book>(book_id, bookDatPath);
    Menu * menu = new Menu();    //menu中间变量
    menu = search<Menu>(book->menu_ID, menuDatPath);

//    for(int i = 0; i < MAX_BORROW; i++) {
//        cout << user->borrow[i] << " ";
//    }
//    cout << endl;

    //判断学生是否借书超上限
    int flag_canBorrow = -1;    //-1不可以借书，通过下面循环找到可以借书的数组位置
    for(int i = 0; i < MAX_BORROW; i++) {
        if(user->borrow[i] == -1) {
            flag_canBorrow = i;
            break;
        }
    }

    //返回-2，该书正在被借阅
    if(book->isBorrowed != -1) {
        addLog("[borrow] status -2 : The book is borrowed. UserID[" + to_string(user->ID) + "] borrow bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] unsuccessfully");

        return -2;
    }

    //返回-3，该书正在被其他人预约
    else if((book->isBooked != -1) && (book->isBooked != user->ID)) {
        addLog("[borrow] status -3 : The book is reserved by other people. UserID[" + to_string(user->ID) + "] borrow bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] unsuccessfully");

        return -3;
    }

    //返回-1，借书超上限
    else if(flag_canBorrow == -1) {
        addLog("[borrow] status -1 : Reach limit. UserID[" + to_string(user->ID) + "] borrow bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] unsuccessfully");
        return -1;
    }

    //成功借阅 0，加入英雄榜 1
    else {

        //判断书籍是否被预约
        int flag_isReserved = 0;
        if (book->isBooked != -1) {
            flag_isReserved = 1;
        }

        //添加record记录
        int record_id = addRecord(user_id, book_id);

        //book状态更新
        book->isBorrowed = record_id;
        book->borrow_num += 1;
        book->isBooked = -1;
        rewrite(book->ID, book, bookDatPath);

        //menu状态更新
        menu->borrowCount += 1;
        menu->remain -= 1;
        if(flag_isReserved == 1) {
            menu->reserveNum -= 1;
            menu->remain += 1;  //被预约了还书时remain不-1
        }
        rewrite(menu->ID, menu, menuDatPath);

        //学生状态更新
        user->all_Borrow += 1;
        user->borrow[flag_canBorrow] = record_id;
        if(flag_isReserved == 1) {
            for(int i = 0; i < MAX_RESERVE; i++) {
                if(user->reserve[i] == book->ID) {
                    user->reserve[i] = -1;
                    break;
                }
            }
        }
        rewrite(user->ID, user, studentDatPath);

//        for(int i = 0; i < MAX_BORROW; i++) {
//            cout << user->borrow[i] << " ";
//        }
//        cout << endl;

        //返回 1，成功借阅并加入英雄榜
        if(user->all_Borrow == heroRankRequireNum) {
            addHeroRank(user->ID);
            addLog("[borrow] status 1 : recordID[" + to_string(record_id) + "] : UserID[" + to_string(user->ID) + "] borrow bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] successfully and the user is added to the hero rank");

            return 1;
        }
        addLog("[borrow] status 0 : recordID[" + to_string(record_id) + "] : UserID[" + to_string(user->ID) + "] borrow bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] successfully");
        return 0;
    }

}

//续借书籍（在原来的基础上，所以已知了ID）
void reborrow(int record_id) {
    Record* tempRecord = new Record;
    tempRecord = search<Record>(record_id, recordDatPath);
    tempRecord->isReborrwed = 1;
    tempRecord->latestReturnTime += REBORROWING_TIME;
    rewrite(record_id, tempRecord, recordDatPath);
    addLog("[reborrow] status 0 : recordID[" + to_string(record_id) + "] reborrow successfully");
}

//归还图书,0正常还书,-1逾期还书, 1还书失败
int returnBook(int record_id) {
//    cout << "start return" << endl;
    Record * record = new Record;
    record = search<Record>(record_id, recordDatPath);
    Student * user = new Student;
    user = search<Student>(record->userId, studentDatPath);
    Book * book = new Book;
    book = search<Book>(record->bookId, bookDatPath);
    Menu * menu = new Menu;
    menu = search<Menu>(book->menu_ID, menuDatPath);

    if(record->status == 1 ) { //record状态是正在借阅
        //判断是否超时
        //record状态更新
        time_t timep;
        time(&timep);
        if(timep > record->latestReturnTime)
            record->status = -1;
        else
            record->status = 0;
        record->returnTime = timep;
        rewrite(record->ID, record, recordDatPath);

        //book状态更新
        book->isBorrowed = -1;
        rewrite(book->ID, book, bookDatPath);

        //menu状态更新
        if(book->isBooked != -1) {      //若书被预约则remain不变
            menu->remain += 1;
            rewrite(menu->ID, menu, menuDatPath);
        }

        //user释放borrow[]对应记录
        for(int i = 0; i < MAX_BORROW; i++) {
            if(user->borrow[i] == record_id) {
                user->borrow[i] = -1;
            }
        }
        rewrite(user->ID, user, studentDatPath);

        if(record->status == -1) {
            addLog("[returnBook] status -1 : Return book late. RecordID[" + to_string(record->ID) + "] : UserID[" + to_string(user->ID) + "] return bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] successfully");
            return -1;
        }

        addLog("[returnBook] status 0 : RecordID[" + to_string(record->ID) + "] : UserID[" + to_string(user->ID) + "] return bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] successfully");
        return 0;
    }
    addLog("[returnBook] status 1 : Error. RecordID[" + to_string(record->ID) + "] : UserID[" + to_string(user->ID) + "] return bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] unsuccessfully");
    return 1;

}

// 0 正常，-1 书籍可直接借阅， -2 书籍已被他人预约， -3 预约数超额
int reserve(int user_id, int book_id) {
//    cout << "--start reserve--" << endl;

    Student * user = new Student();   //准确查找
    user = search<Student>(user_id, studentDatPath); //user中间变量
    Book * book = new Book();    //book中间变量
    book = search<Book>(book_id, bookDatPath);
    Menu * menu = new Menu();    //menu中间变量
    menu = search<Menu>(book->menu_ID, menuDatPath);

    //判断学生是否预约超上限
    int flag_canReserve = -1;    //-1不可以预约，通过下面循环找到可以预约的数组位置
    for(int i = 0; i < MAX_RESERVE; i++) {
        if(user->reserve[i] == -1) {
            flag_canReserve = i;
            break;
        }
    }



    //返回-2，书籍已被他人预约
    if (book->isBooked != -1) {
        addLog("[reserve] status -2 : The book is reserved by other people. UserID[" + to_string(user->ID) + "] reserve bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] unsuccessfully");
        return -2;
    }

    //返回-1，书籍可直接借阅
    else if (book->isBorrowed == -1) {
        addLog("[reserve] status -1 : The book can be borrowed. UserID[" + to_string(user->ID) + "] reserve bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] unsuccessfully");
        return -1;
    }

    //返回-3，预约超上限
    else if(flag_canReserve == -1) {
        addLog("[reserve] status -1 : Reach limit. UserID[" + to_string(user->ID) + "] reserve bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] unsuccessfully");
        return -3;
    }

    //成功预约 0
    else {
        addLog("[reserve] status 0 : UserID[" + to_string(user->ID) + "] reserve bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] successfully");

        //book状态更新
        book->isBooked = user->ID;
        rewrite(book->ID, book, bookDatPath);

        //menu状态更新
        menu->reserveNum += 1;
        rewrite(menu->ID, menu, menuDatPath);

        //学生状态更新
        user->reserve[flag_canReserve] = book->ID;
        rewrite(user->ID, user, studentDatPath);

//        for(int i = 0; i < MAX_BORROW; i++) {
//            cout << user->borrow[i] << " ";
//        }
//        cout << endl;
        return 0;
    }
}

//取消预约
int cancelReserve(int user_id, int book_id) {
//    cout << "--start cancel reservation--" << endl;

    Student * user = new Student();   //准确查找
    user = search<Student>(user_id, studentDatPath); //user中间变量
    Book * book = new Book();    //book中间变量
    book = search<Book>(book_id, bookDatPath);
    Menu * menu = new Menu();    //menu中间变量
    menu = search<Menu>(book->menu_ID, menuDatPath);

    //用户状态更新
    for(int i = 0; i < MAX_RESERVE; i++) {
        if(user->reserve[i] == book->ID) {
            user->reserve[i] = -1;
        }
    }
    rewrite(user->ID, user, studentDatPath);

    //menu状态更新
    if(book->isBorrowed == -1) {    //如果此时书可以借，取消预约menu->remain要增加回
        menu->remain += 1;
    }
    menu->reserveNum -= 1;
    rewrite(menu->ID, menu, menuDatPath);

    //book状态更新
    book->isBooked = -1;
    rewrite(book->ID, book, bookDatPath);

    addLog("[cancelReserve] status 0 : UserID[" + to_string(user->ID) + "] cancel reservation bookID[" + to_string(book->ID) + "] in menuID[" + to_string(menu->ID) + "] successfully");

    return 0;
}

//查询书籍目录 按照isbn返回一个值
Menu* search_onemenuReturn( string field, const char* path) {
    auto size = sizeof (Menu);//书籍类的大小
    FILE *file = openfile(path, size); //打开文件
    fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾
    auto offset = ftell(file);//ftell得到文件从指针到文件头的大小（offset是文件总大小）
    int count = offset / size; //确定文件总学生信息
    Menu* temp = new Menu;                         //新建一个临时储存类型
    memset(temp, 0, sizeof (Menu));             //所有信息先赋值为0
    Menu* menu = new Menu;                         //新建一个临时储存类型
    memset(menu, 0, sizeof (Menu));             //所有信息先赋值为0
    fseek(file, 0, SEEK_SET);   //将指针指到文件头
    char* matchField;

    matchField = menu->ISBN;
    for(int i = 0; i <= count; i++) { //遍历数据
        fread(menu, size, 1, file); //依次读出并对比学号
        if(strcmp(matchField, field.c_str()) == 0 && menu->countNum > 0) {
            return menu;         //得到学号就该学生
        }

    }
    fclose(file);                           //关闭文件
//    return NULL;
    return temp;
}

//多返回搜索，可调节是否使用模糊搜索,参数为（string 是否使用模糊搜索，string 表中的要搜索的字段，string 搜索关键词，文件路径）
//按照作者和书名返回多个
vector<Menu*> search_multiplemenuReturn(string fuzzySearchCondition, string field, string searchKey, const char* path) {
    auto size = sizeof (Menu);                 //学生类的大小
    FILE *file = openfile(path, size);      //打开文件
    fseek(file, 0, SEEK_END);               //fseek将文件指针指到文件末尾
    auto offset = ftell(file);              //ftell得到文件从指针到文件头的大小（offset是文件总大小）
    int count = offset / size;              //确定文件总学生信息
    Menu* temp = new Menu;                        //新建一个临时储存类型
    memset(temp, 0, sizeof (Menu));            //所有信息先赋值为0
    fseek(file, 0, SEEK_SET);               //将指针指到文件头

    vector<Menu*> matchList;
    matchList.clear();

    char* matchField = NULL;


    //不使用模糊搜索
    if(fuzzySearchCondition == "notFuzzySearch") {
        for(int i = 0; i < count; i++) {                             //遍历数据
            fread(temp, size, 1, file);                              //依次读出并对比学号

            if(strcmp(matchField, searchKey.c_str()) == 0 && temp->countNum > 0) {     //！！！大坑，不能直接存temp，temp是指针位置最后会跳到文件尾
                Menu* temp2 = new Menu;                                    //每次新建一个空间储存新找到的数据结构体
                memset(temp2, 0, sizeof (Menu));                        //新建的结构体所有信息先赋值为0
                memcpy(temp2, temp, sizeof(Menu));                      //把temp内存整体复制到temp2
                matchList.push_back(temp2);
            }
        }
    }
    //使用模糊搜索
    else if(fuzzySearchCondition == "useFuzzySearch") {
        for(int i = 0; i < count; i++) {                            //遍历数据
            fread(temp, size, 1, file);                             //依次读出并对比学号
            if(field == "writer")
                matchField = temp->writer;
            if(field == "name")
                matchField = temp->name;
            if(field == "ISBN")
                matchField = temp->ISBN;
            string tempStr = matchField;
            if(tempStr.find(searchKey.c_str()) != tempStr.npos && temp->countNum > 0) { //！！！大坑，不能直接存temp，temp是指针位置最后会跳到文件尾
                Menu* temp2 = new Menu;                                   //每次新建一个空间储存新找到的数据结构体
                memset(temp2, 0, sizeof (Menu));                       //新建的结构体所有信息先赋值为0
                memcpy(temp2, temp, sizeof(Menu));                     //把temp内存整体复制到temp2
                matchList.push_back(temp2);
            }

        }
    }
    fclose(file);
    return matchList;

}
//按照menu_id返回多个书
vector<Book*> search_multiplebookReturn(string fuzzySearchCondition, string field, int searchKey, const char* path) {
    auto size = sizeof (Book);                 //学生类的大小
    FILE *file = openfile(path, size);      //打开文件
    fseek(file, 0, SEEK_END);               //fseek将文件指针指到文件末尾
    auto offset = ftell(file);              //ftell得到文件从指针到文件头的大小（offset是文件总大小）
    int count = offset / size;              //确定文件总学生信息
    Book* temp = new Book;                        //新建一个临时储存类型
    memset(temp, 0, sizeof (Book));            //所有信息先赋值为0
    fseek(file, 0, SEEK_SET);               //将指针指到文件头

    vector<Book*> matchList;
    matchList.clear();

    int matchField = -1;



    //不使用模糊搜索
    if(fuzzySearchCondition == "notFuzzySearch") {
        for(int i = 0; i < count; i++) {                             //遍历数据
            fread(temp, size, 1, file);                              //依次读出并对比学号
            if(field == "menu_id")
                matchField = searchKey;
            if(matchField == temp->menu_ID && temp->exist == 1) {   //！！！大坑，不能直接存temp，temp是指针位置最后会跳到文件尾
                Book* temp2 = new Book;                                    //每次新建一个空间储存新找到的数据结构体
                memset(temp2, 0, sizeof (Book));                        //新建的结构体所有信息先赋值为0
                memcpy(temp2, temp, sizeof(Book));                      //把temp内存整体复制到temp2
                matchList.push_back(temp2);
            }

        }
    }
//    //使用模糊搜索
//    else if(fuzzySearchCondition == "useFuzzySearch") {
//        for(int i = 0; i < count; i++) {                            //遍历数据
//            fread(temp, size, 1, file);                             //依次读出并对比学号

//            string tempStr = matchField;
//            if(tempStr.find(searchKey.c_str()) != tempStr.npos) {   //！！！大坑，不能直接存temp，temp是指针位置最后会跳到文件尾
//                Book* temp2 = new Book;                                   //每次新建一个空间储存新找到的数据结构体
//                memset(temp2, 0, sizeof (Book));                       //新建的结构体所有信息先赋值为0
//                memcpy(temp2, temp, sizeof(Book));                     //把temp内存整体复制到temp2
//                matchList.push_back(temp2);
//            }

//        }
//    }
    fclose(file);
    return matchList;
}

vector<Record*> search_multiplerecordReturn(string fuzzySearchCondition, string field, int searchKey, const char* path) {
    auto size = sizeof (Record);                 //学生类的大小
    FILE *file = openfile(path, size);      //打开文件
    fseek(file, 0, SEEK_END);               //fseek将文件指针指到文件末尾
    auto offset = ftell(file);              //ftell得到文件从指针到文件头的大小（offset是文件总大小）
    int count = offset / size;              //确定文件总学生信息
    Record* temp = new Record;                        //新建一个临时储存类型
    memset(temp, 0, sizeof (Record));            //所有信息先赋值为0
    fseek(file, 0, SEEK_SET);               //将指针指到文件头

    vector<Record*> matchList;
    matchList.clear();

    int matchField = -1;



    //不使用模糊搜索
    if(fuzzySearchCondition == "notFuzzySearch") {
        for(int i = 0; i < count; i++) {                             //遍历数据
            fread(temp, size, 1, file);                              //依次读出并对比学号
            if(field == "userID")
                matchField = temp->userId;
            if(field == "bookID")
                matchField = temp->bookId;
            if(matchField == searchKey) {       //！！！大坑，不能直接存temp，temp是指针位置最后会跳到文件尾
                Record* temp2 = new Record;                                    //每次新建一个空间储存新找到的数据结构体
                memset(temp2, 0, sizeof (Record));                        //新建的结构体所有信息先赋值为0
                memcpy(temp2, temp, sizeof(Record));                      //把temp内存整体复制到temp2
                matchList.push_back(temp2);
            }

        }
    }

    fclose(file);
    return matchList;
}


vector<Record*> search_borrowing(vector<Record*>recordList) {
    vector<Record*> newList;
    int all = recordList.size();
    for(int i = 0; i < all; i++) {
        if(recordList[i]->status == 1) {
            Record *t = new Record;
            memset(t, 0, sizeof (Record));
            memcpy(t, recordList[i], sizeof(Record));
            newList.push_back(t);
        }
        if(newList.size() == 3)
            break;
    }
    return newList;
}


}
